<template>
  <!-- 手机号 -->
  <el-form
    :model="loginData"
    label-position="left"
    ref="phoneForm"
  >
    <div class="phone" v-if="!isContinue">
      <div class="wml" @click="changeToQrLogin">
        <svg width="72" height="72" viewBox="0 0 72 72" fill="none"
             xmlns="http://www.w3.org/2000/svg">
          <mask id="mask0_13456_28587" maskUnits="userSpaceOnUse" x="0" y="0" width="72" height="72"
                style="mask-type: alpha;">
            <path d="M0 0H64C68.4183 0 72 3.58172 72 8V72L0 0Z" fill="white"></path>
          </mask>
          <g mask="url(#mask0_13456_28587)">
            <path fill-rule="evenodd" clip-rule="evenodd"
                  d="M14 10H5V15H14V10ZM17 10H34V15H17V10ZM37 10H62V35H37V10ZM41 14H58V31H41V14ZM54 18H45V27H54V18ZM17 18H34V35H17V18ZM20.6429 21.6429H30.3572V31.3572H20.6429V21.6429ZM27.9285 24.0714H23.0714V28.9286H27.9285V24.0714ZM26 38H37V46H26V38ZM40 38H45V43H40V38ZM62 54H57V72H62V54ZM48 38H62V43H48V38ZM62 46H57V51H62V46ZM54 46H41V59H54V46ZM50 50H45V55H50V50Z"
                  fill="#7BA3FF"></path>
          </g>
        </svg>
        <el-text>
          扫码登录
        </el-text>

      </div>
      <el-text class="wel-title">
        Hello 喵喵记账
      </el-text>

      <el-text class="sub-title">
        登录账号,开启全新体验
      </el-text>
      <el-form-item class="input-phone"
                    :class="{ 'is-error': phoneError }">
        <el-input ref="phoneInput"
                  placeholder="请输入手机号码"
                  v-model="loginData.phone"
                  :class="{ 'error-border': phoneError }"/>
      </el-form-item>
      <el-form-item class="check">
        <el-checkbox v-model="isChecked"/>
        <el-text>
          同意
        </el-text>
        <el-link type="primary" underline="never">
          喵喵记账账号服务条款
        </el-link>
        <el-text>
          、
        </el-text>
        <el-link type="primary" underline="never">
          喵喵记账平台服务条款
        </el-link>
        <el-text>
          和
        </el-text>
        <el-link type="primary" underline="never">
          隐私政策
        </el-link>
      </el-form-item>

      <el-form-item class="submit-btn">
        <el-button type="primary" @click.prevent="showPhoneCodeForm()">
          下一步
        </el-button>
      </el-form-item>
      <el-form-item class="extra-options">
        <el-link underline="never" @click="changeToPwLogin">
          密码登录
        </el-link>
        &nbsp;| &nbsp;
        <el-link underline="never" @click="changeToRegister">
          注册新账号
        </el-link>
      </el-form-item>
    </div>

    <!--验证码-->
    <div v-else class="v-code">
      <el-icon size="20" style="cursor: pointer" @click="isContinue =false">
        <el-ArrowLeft/>
      </el-icon>
      <el-text class="wel-title" style=" margin: 14px 0 8px;">
        请完成短信校验
      </el-text>
      <el-text class="sub-title">
        已发送至 {{ phoneMask }}
      </el-text>
      <el-form-item class="input-v-code"
      >
        <el-input
          placeholder="请输入短信验证码"
          v-model="loginData.code"
        >
          <template #append>
            <el-text v-if="sendTimeOut" style="color: #bcc0cb;" unselectable="on">
              已发送{{ sendTimeOut }}s
            </el-text>
            <el-link v-else underline="never" style="color:#3370ff;" @click="sendVCode">
              重新发送
            </el-link>
          </template>
        </el-input>
      </el-form-item>
      <el-text class="sub-title" style="margin-top:10px;" unselectable="on">
        无法收到短信?
      </el-text>

      <el-form-item class="submit-btn" style="margin-top: 180px">
        <el-button type="primary" @click="login">
          登录
        </el-button>
      </el-form-item>
    </div>
  </el-form>


</template>

<script setup lang="ts">

import {computed, onUnmounted, reactive, ref} from "vue"
import {ElMessage, ElNotification} from "element-plus"
import {nextTick} from 'vue'
import type {phoneLoginForm} from "@/api/login/types.ts";
import {maskPhone} from "@/utils/stringUtils.ts";
import {sendCode, phoneLogin} from "@/api/login";
import {useTokenStore} from "@/stores/useTokenStore.ts";
import {useRouter} from "vue-router";

const emit = defineEmits(["change-type"])

//切换到二维码登录
function changeToQrLogin() {
  emit('change-type', 2)
}

//切换到账号密码登录
function changeToPwLogin() {
  emit('change-type', 3)
}

//切换到注册
function changeToRegister() {
  emit('change-type', 4)
}

// 用于获取输入框DOM引用
const phoneForm = ref();
const phoneError = ref(false)
const phoneInput = ref()
//勾选
const isChecked = ref<boolean>(false);
//是否下一步
const isContinue = ref<boolean>(false);


const loginData = reactive<phoneLoginForm>({
  phone: "",
  code: ""
})


const phoneMask = computed(() => {
  return maskPhone(loginData.phone);
})

// 校验手机号函数
function validatePhone(phone: string) {

  if (!phone) {
    phoneError.value = true
    ElMessage.error('请输入手机号')
    return false
  } else if (phone.length !== 11) {
    phoneError.value = true
    ElMessage.error('请输入正确的手机号')
    return false
  } else if (!/^1[3456789]\d{9}$/.test(phone)) {
    ElMessage.error('请输入正确格式的手机号')
    phoneError.value = true
    return false
  }
  phoneError.value = false
  return true
}

// 修改showPhoneCodeForm函数
async function showPhoneCodeForm(): Promise<void> {
  if (!validatePhone(loginData.phone)) {
    await nextTick()
    phoneInput.value?.focus()
    return
  }

  if (!isChecked.value) {
    ElMessage.error('请先阅读并同意相关协议')
    return
  }

  isContinue.value = !isContinue.value
  //发送验证码
  await sendVCode();
}


const sendTimeOut = ref<number>(0);
let countdownTimer: number | null = null;

//发送验证码
async function sendVCode() {
  if (sendTimeOut.value > 0) {
    return
  }
  try {
    //发送验证码
    await sendCode(loginData.phone).then(() => {
      sendTimeOut.value = 60;
      countdownTimer = setInterval(() => {
        sendTimeOut.value--;
        if (sendTimeOut.value <= 0 && countdownTimer) {
          clearInterval(countdownTimer);
          countdownTimer = null;
        }
      }, 1000)

      ElMessage.success('验证码已发送');
    })
  } catch (error) {
    console.log("发送验证码失败", error)
  }
}


//清除定时器
onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
    countdownTimer = null;
  }
})


const router = useRouter();

//登录
function login() {
  phoneLogin(loginData).then((res) => {
    //存储token
    useTokenStore().setToken(res?.data ?? null);
    //弹出提示
    ElNotification.success({
      title: 'Hi~',
      message: `${useTokenStore().username}欢迎回来`,
      duration: 2000
    })
    //跳转到首页
    router.push("/");
  })

}
</script>

<style scoped lang="scss">

//强制样式
.el-input {
  :deep(.el-input__inner) {
    color: #101010;
  }
}

//标题
.wel-title {
  margin: 24px 0 8px;
  padding: 0;
  display: block;
  font-size: 24px;
  color: #21293a;
  font-weight: 500;
}

//副语
.sub-title {
  display: block;
  font-size: 14px;
  color: #9095a2;
  line-height: 22px;
}


//登录按钮
.submit-btn {
  position: relative;
  top: -20px;

  .el-button {
    font-size: 20px;
    width: 352px;
    height: 48px;
    background-color: #3370ff;
  }
}


//手机号
.phone {

  //扫码svg
  .wml {
    cursor: pointer;
    height: 72px;
    position: absolute;
    right: 0;
    top: 0;
    width: 72px;
    z-index: 2;


    .el-text {
      position: absolute;
      padding: 6px 8px;
      right: 72px;
      top: 10px;
      background-color: #4573f6;
      color: #fff;
      font-weight: 400;
      line-height: 20px;
      white-space: nowrap;
      border-radius: 2px;
      opacity: 0;

      // 新增箭头样式
      &::after {
        content: "";
        position: absolute;
        right: -8px; // 从文字框右侧伸出
        top: 50%;
        transform: translateY(-50%);
        width: 0;
        height: 0;
        border-style: solid;
        border-width: 6px 0 6px 8px; // 控制箭头大小和方向
        border-color: transparent transparent transparent #4573f6; // 箭头颜色与背景一致
      }


    }

    &:hover .el-text {
      opacity: 1;
      transition: opacity 0.3s ease-in-out;
    }


  }


  //手机号登录输入框
  .input-phone {
    margin-top: 24px;
    font-size: 16px;


    :deep(.el-input .error-border) {
      .el-input__wrapper {
        box-shadow: 0 0 0 1px var(--el-color-danger) inset !important;

        &:hover {
          box-shadow: 0 0 0 1px var(--el-color-danger) inset !important;
        }
      }
    }

    .el-input {
      width: 326px;
      height: 46px;
      --el-text-color-placeholder: #585e6d;
      font-size: 16px;
    }
  }

  //勾选
  .check {
    margin-bottom: 120px;

    :deep(.el-text ) {
      --el-text-color: #101010;
    }

    .el-checkbox {
      margin-right: 10px;
    }
  }

  //额外选项
  .extra-options {
    position: relative;
    top: -35px;
    left: 100px;
    width: 200px;
    display: flex;
    flex-direction: row;
    justify-content: center;
    text-align: center;
  }


}

//验证码
.v-code {
  .el-icon {
    color: #101010;
  }

  //验证码输入框
  .input-v-code {
    margin: 24px 0 10px;
    padding: 1px;
    font-size: 16px;
    border: #e5eaed solid 1px;
    border-radius: 4px;


    // 焦点状态样式
    &:focus-within {
      border-color: #3370ff;
      box-shadow: 0 0 0 1px #3370ff inset;
    }


    // 悬浮样式
    &:hover {
      border-color: #3370ff;
      box-shadow: 0 0 0 1px #3370ff inset;
    }

    :deep(.el-input__wrapper ) {
      box-shadow: none;
    }

    .el-input {
      width: 326px;
      height: 46px;
      --el-text-color-placeholder: #999eaa;
      font-size: 16px;


      :deep( .el-input-group__append) {
        position: relative;
        right: -10px;
        padding: 0;
        box-shadow: none;
        border: none;
        background-color: #fff;
        font-size: 14px;
      }
    }


  }
}

</style>
